package com.zhuliwei.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.NoticeDto;
import com.zhuliwei.domain.entity.Notice;
import com.zhuliwei.domain.vo.NoticeVo;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.mapper.ArticleMapper;
import com.zhuliwei.mapper.UserMapper;
import com.zhuliwei.service.NoticeService;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.SecurityUtils;
import com.zhuliwei.utils.WebUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 通知管理控制层
 *
 * @author 朱力维
 * @time 2024/12/1 16:03
 **/
@RestController
@RequestMapping("/content/notice")
@Api(tags = "通知", description = "通知管理相关接口")
public class NoticeController {
    @Resource
    private NoticeService noticeService;

    @Resource
    private UserMapper userMapper;
    @Resource
    private ArticleMapper articleMapper;

    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('content:notice:list')")
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, NoticeDto noticeDto) {
        PageVo pageVo = noticeService.pageNoticeList(pageNum, pageSize, noticeDto);
        return ResponseResult.okResult(pageVo);
    }

    @PostMapping
    @PreAuthorize("@ps.hasPermission('content:notice:add')")
    public ResponseResult addNotice(@RequestBody NoticeDto noticeDto) {
        if (!StringUtils.hasText(noticeDto.getContent())) {
            return ResponseResult.errorResult(500, "通知内容不能为空");
        }
        if (CollectionUtils.isEmpty(noticeDto.getUserIds())) {
            return ResponseResult.errorResult(500, "用户不能为空");
        }
        noticeDto.getUserIds().forEach((item->{
            Notice notice = BeanCopyUtils.copyBean(noticeDto, Notice.class);
            notice.setUserId(item);
            notice.setType(SystemConstants.NOTICE_TYPE_SYSTEM);
            notice.setCreateTime(new Date());
            notice.setCreateBy(SecurityUtils.getUserId());
            noticeService.save(notice);
        }));
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@ps.hasPermission('content:notice:delete')")
    public ResponseResult deleteNotice(@PathVariable List<String> ids) {
        noticeService.removeByIds(ids);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult noticeDetail(@PathVariable String id) {
        Notice notice = noticeService.getById(id);
        NoticeVo noticeVo = BeanCopyUtils.copyBean(notice, NoticeVo.class);
        noticeVo.setUserName(userMapper.selectById(noticeVo.getUserId()).getUserName());
        if (StringUtils.hasText(noticeVo.getArticleId()))
            noticeVo.setArticleName(articleMapper.selectById(noticeVo.getArticleId()).getTitle());
        return ResponseResult.okResult(noticeVo);
    }

    @PutMapping
    @PreAuthorize("@ps.hasPermission('content:notice:update')")
    public ResponseResult updateNotice(@RequestBody NoticeDto noticeDto) {
        if (!StringUtils.hasText(noticeDto.getContent())) {
            return ResponseResult.errorResult(500, "通知内容不能为空");
        }
        Notice notice = BeanCopyUtils.copyBean(noticeDto, Notice.class);
        noticeService.updateById(notice);
        return ResponseResult.okResult();
    }

    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('content:notice:export')")
    public void export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("消息通知.xlsx", response);
            //获取需要导出的数据
            List<Notice> notices = noticeService.list();
            List<NoticeVo> noticeVos = BeanCopyUtils.copyBeanList(notices, NoticeVo.class);
            noticeVos.forEach(noticeVo -> {
                noticeVo.setUserName(userMapper.selectById(noticeVo.getUserId()).getUserName());
                noticeVo.setArticleName(articleMapper.selectById(noticeVo.getArticleId()).getTitle());
            });
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), NoticeVo.class).autoCloseStream(Boolean.FALSE).sheet("消息通知")
                    .doWrite(noticeVos);
        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
